var papermanagermodule = angular.module("papermanager",['ui.tree','dropdownApp','720kb.tooltips', 'tm.pagination','vModal','Common', 'knowledgebaseS',  'PensonSelector','loadModule','knowledgeSelector','knowledgeDeleteBox','btnconqitk'])
 .factory('resultStatisFactory', function (vModal) {
    return vModal({
        controller: 'resultstatisModal',
        controllerAs: 'resultStatisFactory',
        templateUrl: '/system/views/examination/examresult.html'
     });
 })
  .factory('errorQuestionFactory', function (vModal) {
    return vModal({
        controller: 'errorQuestionModal',
        controllerAs: 'errorQuestionFactory',
        templateUrl: '/system/views/examination/examerrorques.html'
     });
 })
.controller('papermanagercontroller', ['$scope', 'resultStatisFactory','errorQuestionFactory','$rootScope', 'sysUserInfo','RequestTrainService','Comm', 'MsgCon', 'Msg','$sce','$stateParams', '$state', function ($scope, resultStatisFactory,errorQuestionFactory,$rootScope,sysUserInfo,RTS,  Comm, MsgCon, Msg,$sce,$stateParams, $state) {
$scope.btnlist = { savefun: false, addinfo: false, editinfo: false, delinfo: false };
    $rootScope.btnTab = "index.Train.papermanager";
    $scope.examToken = sysUserInfo.getuserinfotoken();

    
    //补考
    $scope.bukao=function(item){
      if(item.paperId==undefined||item.paperId==null){
          return;
      }
      $scope.examLoading=true;
      RTS.resitTask({paperId:item.paperId,userId:sysUserInfo.getuserinfo().user_ID}).then(function (response) {
          $scope.examLoading=false;
          if (response.errorcode == "0") {
              Msg.success("添加补考成功！");
              $scope.GetList();
          } else if(response.errorcode=="25"){
              Msg.warning("该试卷未绑定任务，无法补考！");
          }else if(response.errorcode=="26"){
              Msg.warning("该试卷已生成补考试卷！");
          }else if(response.errorcode=="27"){
              Msg.warning("当前试卷所在的任务无人员!");
          }else {
              Msg.error("添加补考失败！");
          }
      }, function errorCallback() {
          $scope.examLoading=false;
          console.log("连接服务器失败！");
      });
}


  
	/*******************************************************初始化*********************************************/
	$scope.params={
		pageIndex:"1",
		pageSize:"10",
		knowledge_Id:"",
		userid: sysUserInfo.getuserinfo().user_ID,
   		orgid: sysUserInfo.getuserinfo().organization_ID,   // 企业id
    	powerLV: sysUserInfo.getuserinfo().powerLV,//登录人的系统角色
    	startDate:"",
    	endDate:"",
    	screenText:"",
    	screenType:"3",
    	orderBy:"desc",
    	orderbyfield:"2"         
    };

      //导出
    $scope.exportExcel = function (item) {
        var paramExport = {export:2, paperid: item.paperId,orderby: "desc",sort: "1",correct: "3",orgid: sysUserInfo.getuserinfo().organization_ID,single: 2};
        RTS.paperStatistics(paramExport).then(function (response) {
            if (response.errorcode == "0" && response.errormsg != undefined && response.errormsg.length > 0) {
                window.location = response.errormsg;
            }
            else if (response.errorcode == "73" || (response.errorcode == "0" && (response.errormsg == undefined || response.errormsg.length <= 0))) {
                setTimeout(function () {
                    $scope.exportExcel(item);
                }, 3000);
                Msg.warning("正在统计请稍后..");
            } else {
                Msg.error("统计失败！");
            }
        }, function errorCallback() {
            console.log("连接服务器失败！");
        });

    }

    /*分页*/
    $scope.paginationConf = {
        currentPage:1,//$location.search().currentPage ? $location.search().currentPage :
        totalItems:0,
        itemsPerPage: 10,
        //pagesLength: 10,
        perPageOptions: [10, 20],
        //rememberPerPage: 'perPageItems',
        onChange: function () {
        	if( (parseInt($scope.params.pageIndex) !=parseInt($scope.paginationConf.currentPage))||(parseInt($scope.params.pageSize) !=parseInt($scope.paginationConf.itemsPerPage))){
        		if($scope.paginationConf.currentPage==0){$scope.paginationConf.currentPage=1;}
        		$scope.params.pageIndex =$scope.paginationConf.currentPage;
        		$scope.params.pageSize = $scope.paginationConf.itemsPerPage;
        		$scope.GetList();
        	}
        }
    }
    //打开学员报表
    $scope.showdetail=false;
    $scope.showDetail=function(obj){
        $scope.showWinForm();
        $scope.detailobj=obj;
    }
    //学员报表回调关闭
    $scope.showWinForm=function(){
        $scope.showdetail=!$scope.showdetail;
    }
    /*******************************************************知识选择器*********************************************/
//配置知识选择器
     $scope.knowConfig = {   // 配置知识选择器的参数
     	menu: ["structure"],
        kssMore:false, //知识结构 是否多选
        kssList:[],    // 知识结构选中列表
        isShow:false,  // 显示知识选择器
    }; 
    /**************************************排序显示***********************************************************/
        $scope.ShowOk=false;//排序显示控制
        $scope.orderby="desc";
        //排序数组
        $scope.OrderName="上传时间";
        $scope.params.orderBy=$scope.orderby;
        $scope.params.orderbyfield=2;
        $scope.orderlist=[{name:"试卷名称",num:1},
        {name:"上传时间",num:2},
//        {name:"通过率",num:3},
        {name:"题目数",num:4}];

        //$scope.params.orderbyfield=1;
        //课件排序
        $scope.OrderByFun=function(Typenum,Ordername){
        	
        	
        
        	if($scope.OrderName==Ordername){
        		if($scope.orderby=="asc"){
        			$scope.orderby="desc";
        		}else{
        			$scope.orderby="asc";
        		}
        	}else{
        		$scope.orderby="desc";
        	}
        	$scope.ShowOk=false;
        	// console.log(Typenum==$scope.params.orderbyfield&&$scope.OrderName==Ordername);
        	// if (Typenum==$scope.params.orderbyfield) {
        	// 	return;
        	// }
        	$scope.OrderName=Ordername;
        	$scope.params.orderBy=$scope.orderby;
        	$scope.params.orderbyfield=Typenum;
        	$scope.GetList();
        }

        /*********************************************************************************筛序初始化*********************************************/
        $scope.buttonshow=true;
        $scope.cite=false;
        $scope.clickFunSHow=function(){
        	$scope.cite=!$scope.cite;
        }
        $scope.screenlist=[
        {name:"试卷名",num:"3"},
        {name:"创建时间查询",num:"1"},
        // {name:"操作人",num:"2"},
        {name:"选择知识分类",num:"4"},
        ];
        $scope.screenobj={name:"试卷名",num:3};
        $scope.screenname="试卷名";
        $scope.screenFun=function(obj){
           $scope.paginationConf.currentPage=1;
          if (obj!=undefined&&obj!=null) {
              $scope.screenobj=obj;
          }
        
				// $scope.clickFunSHow();
				$scope.buttonshow=true;
				if ($scope.screenobj.num=="1") {
					$scope.screentimeshow=true;
				}else {
					$scope.screentimeshow=false;
				}
				$scope.searchText="";
				
				switch ($scope.screenobj.num) {
					case"3":
					$scope.screenname="试卷名";
					break;
					case"2":
					$scope.screenname="操作人";
					break;
					case"4":
					$scope.knowConfig.isShow=true;
					$scope.buttonshow=false;
					break;
				}
				$scope.params.screenType=$scope.screenobj.num;
			}


 //查询按钮
 $scope.ButtonGet=function(){
 	$scope.params.screenType=$scope.screenobj.num;
 	$scope.params.screenText=$scope.searchText;
 	$scope.params.startDate=document.getElementById("startTime").value;
 	$scope.params.endDate=document.getElementById("endTime").value;
 	$scope.GetList();
 }

//知识结构选中
$scope.onCallbackSer = function(obj){
	$scope.knowConfig.isShow=false;
	if($scope.knowConfig.kssList != null && $scope.knowConfig.kssList.length >0){
		$scope.params.knowledge_Id= $scope.knowConfig.kssList[0].knowledge_Id;
		$scope.searchText=$scope.knowConfig.kssList[0].knowledge_Name;
		$scope.knowConfig.knowledge_Id=$scope.knowConfig.kssList[0].knowledge_Id;
		$scope.GetList();
	}else{
		$scope.params.knowledge_Id="";
	}

}
/*******************************************************查询考试列表*********************************************/
$scope.headurl=$rootScope.requestUrl;

 //查询试卷列表
 $scope.GetList=function(){
 	if($scope.isloading){
 		Msg.info("正在查询，请稍后!");
 		return;
 	}
    $scope.selectList=[];    
 	$scope.examLoading=true;
    //findByPaperPageSelectAndTrim
 	RTS.findPaperPage($scope.params).then(function(data){
    	
 		$scope.examLoading=false;      

 		if (data.errorcode == "0") {
 			$scope.List=data.datas;
      
 			if ($scope.List==undefined|| $scope.List.length<=0) {
 				// Msg.error("暂未找到数据");
 				return;
 			}else {
 				$scope.paginationConf.totalItems = data.numCount;
 				$scope.paginationConf.currentPage = data.pageIndex;  
               
 			}
 		}else{

 			Msg.error("请求数据有误");
 		}
 	}, function callback() {
 		Msg.error("请求数据有误");
 		$scope.isloading=false;   
 	});
 }
 $scope.bindpaperDifficulty=function(num){

 	var objname="";
 	$scope.paperDifficultylist.forEach(function(domobj){

 		if (domobj.num==num) {
 			objname=domobj.name;
 			return;
 		}
 	});
 	return objname;
 }
 

 /****************************************************新增编辑页面********************************************************************************/
   //新增
 $scope.addinfo=function(){
    $scope.isHideFun(0);
 }

  //列表编辑图标
 $scope.addinfo=function(obj){
    if(!$scope.btnlist.editinfo){
        Msg.warning("无权限操作！");
        return;
    }
    $scope.selectList=[obj];
    $scope.isHideFun(1);
 }
 
 //编辑
 $scope.editinfo=function(){
    $scope.isHideFun(1);
 }
 
 $scope.TitleStyle=function (obj) {
   if (obj.paper_Random!="1") {
   return{width:"19.5%"};
 }else {
     return{width:"19.5%",color: "#39f",cursor: "pointer"};
 }
}
   	$scope.windowsClose=false; //窗口关闭
     $scope.Editquestion=function(obj){ 

      if (obj.paper_Random!="1"&&obj.paper_Random!=undefined) {
         return Msg.info("随机卷无法查看详细题目!");
      }
     id=obj.paperId;
     if (id!=""&&id!=undefined) {
        $state.go("index.Train.question",{examid:id}); 
      return;
     }     
      if ($scope.selectList.length<=0) {

              return Msg.warning("请选择要编辑的试卷!");
            }else if($scope.selectList.length>1){
              return Msg.warning("只能选择一份试卷编辑!");
            }else{
               $state.go("index.Train.question",{examid:$scope.selectList[0].paperId}); 
            }
    }

    $scope.showSaveButton=false;
     $scope.isHideFun=function(val){//新增编辑页显示隐藏
      
      $scope.showSaveButton=false;
     $scope.personDataUser.UserList=[];
   		$scope.initPaerobj();
   		if (val==0) {//新增

   		}else if(val==1) {
   			if ($scope.selectList.length<=0) {
   				return Msg.warning("请选择要编辑的试卷!");
   			}else if($scope.selectList.length>1){
   				return Msg.warning("只能选择一份试卷编辑!");
   			}else{
                if($scope.selectList[0].paper_Random=="0"&&$scope.selectList[0].examCount!=undefined&&$scope.selectList[0].examCount>0){
                    $scope.showSaveButton=true;
                    //return Msg.warning("该试卷已有学员学习，不可编辑!");
                }
   				$scope.GetExamObj();
   			}
   		}else if(val ==2){
   			$scope.OpenQueHtml(data.paperId);
   		}
   		$scope.windowsClose=!$scope.windowsClose;
   	}
   //编辑 获取试卷对象
   $scope.GetExamObj=function(){
   	$scope.isloading=true;
   	RTS.findPaperByid({paper_id:$scope.selectList[0].paperId,userid: sysUserInfo.getuserinfo().user_ID,
   			orgid: sysUserInfo.getuserinfo().organization_ID,   // 企业id
   			powerLV: sysUserInfo.getuserinfo().powerLV}).then(function(data){
   				$scope.isloading=false;
   				if (data.errorcode == "0") {
   					$scope.paperObj=data.data;
                     $scope.getPerson();//获取负责人
                    //初始积分
                    if($scope.paperObj.integral!=undefined){
                        $scope.paperObj.integral=parseInt($scope.paperObj.integral);
                    }else{
                        $scope.paperObj.integral=0;
                    }

                    if($scope.paperObj.cutOutTimes==undefined){
                      $scope.paperObj.cutOutTimes=3;
                    }

                     if($scope.paperObj.answerTime!=undefined){
                        $scope.paperObj.answerTime=parseInt($scope.paperObj.answerTime);
                    }else{
                        $scope.paperObj.answerTime=0;
                    }
   					if($scope.paperObj.paper_Random != 0 || $scope.paperObj.rule == undefined){ // 非随机试卷
						$scope.paperObj.Rule = []; //随机试卷规则
					}else{
   						$scope.paperObj.Rule = JSON.parse($scope.paperObj.rule); // 规则
   						$scope.paperObj.repetitionRate = $scope.paperObj.paperCount; //重复率
   					}   				
   					$scope.paperObj.userid= sysUserInfo.getuserinfo().user_ID;
   					$scope.paperObj.orgid= sysUserInfo.getuserinfo().organization_ID;// 企业id
    				$scope.paperObj.powerLV= sysUserInfo.getuserinfo().powerLV;//登录人的系统角色
    				$scope.paperObj.userName=sysUserInfo.getuserinfo().user_Name;
    				//$scope.paperObj.orgName=sysUsepaperCountrInfo.getuserinfo().organization_Name;
    			}else if(data.errorcode == "95"){
                    Msg.warning("试卷还在生成中，请稍后重新打开！");
                }else{
    				Msg.error("请求数据有误,无法进行编辑");
    			}
    		},function callback() {
    			Msg.error("请求数据有误");
    			$scope.isloading=false;   
    		});
             
   		}

   		$scope.paperDifficultylist=[
   		
   		{"name":"简单","num":"1"},
   		{"name":"一般","num":"2"},
   		{"name":"困难","num":"3"}
   	
   		];

   	 //声明试卷对象
   	 $scope.initPaerobj=function(){
   	 	$scope.paperObj={
   	 		userid: sysUserInfo.getuserinfo().user_ID,
   			orgid: sysUserInfo.getuserinfo().organization_ID,   // 企业id
    		powerLV: sysUserInfo.getuserinfo().powerLV,//登录人的系统角色
    		userName:sysUserInfo.getuserinfo().user_Name,
    		orgName:sysUserInfo.getuserinfo().organization_Name,
            integral:0,
    		paper_id:"",
    		paperName:"",
			knowledge_Name:"",//知识结构分类名称
			knowledge_Id:"",
			answerTime:"",
			passGrade:"",
			examCount:0,
			paper_Random:"1",
			create_Id: sysUserInfo.getuserinfo().user_ID,
			create_Name:sysUserInfo.getuserinfo().user_Name,
			Rule:[],
			repetitionRate:2,
            huiguFlag:"1",
      paperDifficulty:"1",
      cutOutTimes:3//可切出次数

		};	
        $scope.sendFlag=true;
        // 标记重新录入还是从题库选题
        $scope.knowConfigQuestions.newQuestionsShow = true;
	}
	
	//配置知识选择器
     $scope.knowConfigAdd = {   // 配置知识选择器的参数
     	menu: ["structure"],
        kssMore:false, //知识结构 是否多选
        kssList:[],    // 知识结构选中列表
        isShow:false,  // 显示知识选择器
    }; 

    //知识结构选中
    $scope.onCallbackSerAdd = function(obj){
    	$scope.knowConfigAdd.isShow=false;
    	if($scope.knowConfigAdd.kssList != null && $scope.knowConfigAdd.kssList.length >0){
    		$scope.paperObj.knowledge_Id= $scope.knowConfigAdd.kssList[0].knowledge_Id;
    		$scope.paperObj.knowledge_Name=$scope.knowConfigAdd.kssList[0].knowledge_Name;
    		$scope.knowConfigAdd.knowledge_Id=$scope.knowConfigAdd.kssList[0].knowledge_Id;
    	}else{
    		$scope.paperObj.knowledge_Id="";
    		$scope.paperObj.knowledge_Name="";
    	}

    }
    //打开不开错题
    $scope.updateHG=function(obj){
        if(obj.huiguFlag==undefined){
            obj.huiguFlag="0";
        }else{
            if(obj.huiguFlag=="1"){
                obj.huiguFlag="0";
            }else{
                obj.huiguFlag="1";
            }
        }
    }
    /*************************************************知识选择器-题库选题***************************************************/    
    //配置
    $scope.knowConfigQuestions = {   // 配置知识选择器的参数
        menu: ["question"],
        ksqMore:true, // 题目  是否多选
        ksqList:[],        // 题目选中列表
        isShow:false,   // 显示知识选择器
        callbackParams: {isClose:true},  // 默认通过窗口关闭
        paperObj:{}, //扩展参数 试卷
        countScore:0,   // 展示当前总分
        newQuestionsShow:true
      };     
      // 监听分数的变化        
      $scope.$watch('questionsScoreList', function (newValue, oldValue, scope) {
        $scope.knowConfigQuestions.countScore = 0;
        angular.forEach($scope.questionsScoreList ,function(data,index){
            if(data.type == 6 || data.type == 7){            
                $scope.knowConfigQuestions.countScore +=data.score * data.cnum;
            }else{
                $scope.knowConfigQuestions.countScore +=data.score * data.num;
            }            
        });
      },true)
    // 试题分数列表 筛选 1 单选 2 多选 3 判断 4 问答 5 填空 6 B型题 7 综合题   
    $scope.callbackQueInitList = [
    {
      name:"单选题",
      type:1,
            num:0,  //题目数量
            score:2 // 单题目分数
        },  // 单选题
        {
          name:"多选题",
          type:2,
          num:0,
          score:2
        },  // 多选题
        {
          name:"判断题",
          type:3,
          num:0,
          score:2
        },  // 判断题
        {
          name:"问答题",
          type:4,
          num:0,
          score:2
        },  // 问答题
        {
          name:"填空题",
          type:5,
          num:0,
          score:2
        },  // 填空题
        {
          name:"B型题",
          type:6,
          num:0,
          cnum:0,
          score:2
        },  // B型题
        {
          name:"综合题",
          type:7,
          num:0,
          cnum:0,
          score:2
        }   // 综合题
         ,{
          name:"找错题",
          type:8,
          num:0,
          score:2
        },  // 多选题
        ];    
    //拷贝到前台数组
    $scope.questionsScoreList = angular.copy($scope.callbackQueInitList);
    // 打开题库选择器
    $scope.questionsOpen =function(obj){       
        if(Comm.isNull(obj)){
            Msg.warning("提示","没有找到录入的试卷");
            return;
        }        
        $scope.knowConfigQuestions.paperObj =obj;
      $scope.knowConfigQuestions.isShow = true;
    }
    // 回调选择的试题
    $scope.onCallbackCheckQuestions = function(){            
        if($scope.knowConfigQuestions.callbackParams.isClose){ // 这个时候是关闭按扭点击的
          $scope.knowConfigQuestions.isShow = false;
          return;
        }       
        if($scope.knowConfigQuestions.ksqList.length <=0){
          Msg.info("提示","请选择您要添加的题目!");
          return;
        }
        //为了提高筛选性能进行删减
        $scope.callbackQuestionsList = angular.copy($scope.knowConfigQuestions.ksqList);
        //每次都 需要初始化
        $scope.questionsScoreList = angular.copy($scope.callbackQueInitList);
        // 处理试题分数 以及显示情况       
        angular.forEach($scope.questionsScoreList,function(qdata,qindex,qarray){    // 试题类型遍历
            angular.forEach($scope.callbackQuestionsList,function(data,index,array){ // 遍历选中的试题                                
                if(qdata.type == data.questions_Type){ // 如果类型相同                                    
                  qdata.num = qdata.num + 1;                   
                    if(data.questions_Type  == "6" || data.questions_Type == "7" ){ // B型题 和综合题需要单独处理
                        // 拆包
                        $scope.bTypenObj = JSON.parse(data.questions_Json);                                               
                        qdata.cnum+= JSON.parse($scope.bTypenObj.answerAnalysis).length;                                             
                      }
                    }
                  });            
          });
        // 正式录入试题
        $scope.setQuestionsScoreShow = true;            
      }
      /*******************************设置分数*************************/
      $scope.setQuestionsScoreShow = false;

    // 取消分数设置
    $scope.closeQuestionsScore = function(){
      $scope.setQuestionsScoreShow = false;    
    }
    // 按钮loading
    $scope.isBtnLoading = false;
    // 保存试题
    $scope.saveQuestionsScore = function(){
    try{
            if($scope.knowConfigQuestions.paperObj.passGrade > $scope.knowConfigQuestions.countScore){
                Msg.info("选题总分应大于等于及格分数");
                return;
            }
        }catch(e){
            Msg.info("选题总分应大于等于及格分数");
            return;
        }
      $scope.paramsQuestionsList = [];
        // 处理集合数据
        angular.forEach($scope.questionsScoreList,function(qdata,qindex,qarray){    // 试题类型遍历
            angular.forEach($scope.knowConfigQuestions.ksqList,function(data,index,array){ // 遍历选中的试题                                
                if(qdata.type == data.questions_Type){ // 如果类型相同    
                    if(data.score == undefined || data.score == null || data.score == ""){
                        data.score = 0;
                    }
                    if(data.questions_Type == "6" || data.questions_Type == "7"){ // B 型题 | 综合题 需要对分数单独处理
                        // 拆包
                        $scope.bTypenObj = JSON.parse(data.questions_Json);                                               
                        $scope.bTypeChile = JSON.parse($scope.bTypenObj.answerAnalysis);                       
                        angular.forEach($scope.bTypeChile,function(chile,cindex,carray){
                          chile.score = parseInt(qdata.score);                
                          data.score += parseInt(chile.score);                            
                        });
                      //转字符串
                       $scope.bTypenObj.answerAnalysis = JSON.stringify($scope.bTypeChile); //回转为字符串
                       data.questions_Json = JSON.stringify($scope.bTypenObj); // 试题对象回转为字符串
                       $scope.paramsQuestionsList.push(data);
                     }else{
                      data.score = parseInt(qdata.score);                    
                      $scope.paramsQuestionsList.push({questions_Id:data.questions_Id,score: qdata.score, questions_Type: data.questions_Type}); 
                    }                                        
                  }
                });            
          });
        $scope.isBtnQuestionsLoading =true;
       // console.log($scope.knowConfigQuestions.ksqList,$scope.knowConfigQuestions.paperObj);
        //发送请求        
        RTS.questionsToPaper({ksqList:$scope.paramsQuestionsList, paper_id:$scope.knowConfigQuestions.paperObj.paper_id}).then(function(response){
          if(response.errorcode == "0"){
                $scope.isBtnQuestionsLoading =false; // 关闭loading       
                $scope.setQuestionsScoreShow = false;   // 关闭 设置分数
                $scope.knowConfigQuestions.isShow = false; // 关闭 选择器
                $scope.knowConfigQuestions.ksqList = []; //初始化选中题目
                $scope.reCreatePaper($scope.knowConfigQuestions.paperObj);                
                $scope.GetList();
                Msg.success("题目导入成功！");
              }else{
                Msg.error("题目导入失败！");
                $scope.isBtnQuestionsLoading =false; // 关闭loading       
              }
            }, function callback() {
              Msg.error("题目导入失败");
            $scope.isBtnQuestionsLoading =false; // 关闭loading       
          });        
      }
      /*************************************************知识选择器-题库选题***************************************************/

    //保存
    $scope.btnSave=function(){
      
      if ($scope.paperObj.answerTime==""){
        Msg.warning("请填写答题时间");
        return;
      }
      if (($scope.paperObj.examCount+"").indexOf(".")!=-1){
        Msg.warning("考试机会格式错误！");
        return;
      }
        if ($scope.paperObj.passGrade==""){
        Msg.warning("请填写合格分数");
        return;
      }
       if ($scope.paperObj.knowledge_Id==""){
        Msg.warning("请选择知识结构");
        return;
      }
      var ruleFlag = false;
      var queNum = 0;
      // 验证规则
      angular.forEach($scope.paperObj.Rule,function(data,index){
        if(parseInt(data.Number_of_questions) > parseInt(data.quescount)){
            Msg.warning("规则中题目的数超出知识分类的题目数");
            ruleFlag = true;               
        }
         queNum+=  data.Number_of_questions;
      });
      if(ruleFlag)
      return;      
      // 分数验证
      if($scope.paperObj.paper_Random==0&&parseInt($scope.paperObj.passGrade) > parseInt($scope.paperObj.totalScore)){
        Msg.warning("合格分数不能大于题目总分！");
        return;
      }
      // 空 无限制
      if($scope.paperObj.examCount == undefined || $scope.paperObj.examCount == null || $scope.paperObj.examCount == "" ){
        $scope.paperObj.examCount = 0;
      }
      $scope.isloading=true;

      var id = "";
      var id = "";
        if (sysUserInfo.getuserinfo().powerLV == "3") {
            id = sysUserInfo.getuserinfo().user_ID;
        }
        //负责人id
        $scope.personDataUser.UserList.forEach(function (data, index) {
            id += (id.length > 0 ? ',' : '') + data.user_ID;
        });
        $scope.paperObj.relationId = id;

    	if ($scope.paperObj.paper_Random==1) {//固定卷
    		RTS.savePaper($scope.paperObj).then(function(data){
    			$scope.isloading=false;
    			$scope.windowsClose=false;   

    			if (data.errorcode == "0") {
                    if ($scope.paperObj.paper_id=="") {
                        if($scope.knowConfigQuestions.newQuestionsShow){    // 新题
                            $scope.OpenQueHtml(data.datas.examobj.paper_id);
                        }else{ //题库选题
                            $scope.questionsOpen(data.datas.examobj);
                        }                        
                    }else {
                       Msg.success("操作成功");
                       //编辑状态重新生成试卷
                       if($scope.sendFlag){
                            $scope.reCreatePaper($scope.paperObj);
                       }
                    }
    				$scope.GetList();
    				$scope.initPaerobj(); 
    			}else{
    				Msg.error("请求数据有误");
    			}
    		},function callback() {
    			Msg.error("请求数据有误");
    			$scope.isloading=false;   
    		});
    	}else{
            if ($scope.paperObj.Rule.length<=0) {
                Msg.warning("请添加组卷规则");
                $scope.isloading=false;
              return;
            }
               if ($scope.paperObj.repetitionRate==undefined||$scope.paperObj.repetitionRate<2) {
                Msg.warning("请选择重复率");
                $scope.isloading=false;
              return;
            }
            if(queNum == 0){
            Msg.warning("抽取的总题目数量为空");
            $scope.isloading=false;
            return;
          }
    		Msg.warning("正在生成随机卷，请稍后");


    		RTS.savePaperByRandom($scope.paperObj).then(function(data){
    			$scope.isloading=false;
    			if (data.errorcode == "0") {
    				$scope.windowsClose=false; 
    				Msg.success("保存成功");
    				$scope.GetList();
    				$scope.initPaerobj();
    			}else{
    				Msg.error("请求数据有误");
    			}
    		},function callback() {
    			Msg.error("请求数据有误");
    			$scope.isloading=false;   
    		});
    	}  	
    }
    //在试卷列表‘编辑’试卷时，需要重新生成试卷
    $scope.reCreatePaper=function(paperObj){
            Msg.info("正在重新生成试卷...");
            //判断必须是在编辑时
            if( paperObj.paper_id!=null&& paperObj.paper_id!=""&& paperObj.paper_id!=undefined){
                            //请求后端
                            RTS.IcreateHtml({userid: sysUserInfo.getuserinfo().user_ID,
   			                orgid: sysUserInfo.getuserinfo().organization_ID,   // 企业id
   			                paper_id:paperObj.paper_id}).then(function(data){
                          if (data.errorcode == "0") {
                                Msg.success("重新生成试卷成功");
                          }else{	
                                Msg.error("重新生成试卷失败");
                          }
                        },function callback() {
                             Msg.error("请求数据有误");
                        });
           }
    }
    //关闭、开启重新生成试卷的按钮
    $scope.AutoNotification=function(){
        $scope.sendFlag=!$scope.sendFlag;
    }
    $scope.ListRush=function(data){
      if (data.knowledge_Id!=$scope.params.knowledge_Id&&$scope.params.knowledge_Id!="") {
        $scope.params.knowledge_Id=="";
        $scope.params.searchText=="";
        GetList();
        return;
      }

    	var index=$scope.containsList($scope.List,data);
    	if (index>=0) {	
    		$scope.List[index]=angular.copy(data);
    	}else{

    		$scope.ListCopy=angular.copy($scope.List);
    		$scope.List=[];
    		$scope.List.push(angular.fromJson(data));
    		$scope.List.push.apply($scope.List,$scope.ListCopy);
        $scope.ListRushSort();
    	}
    }
    $scope.ListRushSort=function () {
     if ($scope.List.length>10) {
      $scope.List.splice($scope.List.length-1,1);
     }
     $scope.ListRushSort();
    }
    //进度条
    $scope.progressbarstyle=function(paper_markCount,paperCount){
     if(typeof(paper_markCount)=="string"){
        paper_markCount=parseInt(paper_markCount);
     }
     if(typeof(paperCount)=="string"){
        paperCount=parseInt(paperCount);
     }
      if (paper_markCount==paperCount&&paperCount==0) { //100%
        return{
          "background-color": "#ffbb46",
          "width": "100%",
          "height":"100%"
        }
      }else if(paper_markCount==paperCount&&paperCount>0){
        return{
                  "background-color": "#41b26d",
                  "width": "100%",
                  "height":"100%"
                }
      }else {
         return{
                        "background-color": "#41b26d",
                        "width": paper_markCount/paperCount*100+"%",
                        "height":"100%"
                      }
      }
    };
    /****提交后****/
    /***********************************************************复选框*****************************************************/
  $scope.selectList=[];//选中之后的对象容器

  $scope.selectAll = function() {
  	$scope.select_all=!$scope.select_all;
  	if ($scope.select_all) {
  		$scope.selectList=angular.copy($scope.List);
  	}else{
  		$scope.selectList=[];
  	}
  };
  $scope.setCheck=function(obj,event){
      event = window.event || event;
 event.stopPropagation();
  	var index=$scope.containsList($scope.selectList,obj);

  	if (index>=0) 
  	{
  		$scope.selectList.splice(index,1);
  	}else {
  		$scope.selectList.push(obj);
  	}

  	if ($scope.selectList.length==$scope.List.length) {
  		$scope.select_all=true;
  	}else{
  		$scope.select_all=false;
  	}
  }

  $scope.containsList = function (arr, obj) {
  	
  	try {
  		var i = arr.length;
  		while (i--) {
  			if (arr[i].paperId === obj.paperId) {
  				return i;
  			}
  		}
  		return -1;
  	} catch (e) {
            // statements
            return -1;
        }
    }
   /***************************************删除************************************************************/
      // 删除信息框的显示隐藏    
    $scope.deleteHide = false; //隐藏状态
    // 隐藏 用于指令回调
    $scope.cancelHide = function(){
        $scope.deleteHide = false; 
    }
    //删除的参数
    $scope.delpaperId={paper_id:[],confirmdel:"0",userid:sysUserInfo.getuserinfo().user_ID};

     $scope.delitem=null;
    $scope.Del=function(obj,index){
            if(!$scope.btnlist.delinfo){
                Msg.warning("无权限操作！");
                return;
            }
            
            if($scope.isloading){
                return "";
            }
            if(index==0||index=="0"||index==undefined||index==""||index==null){
                $scope.delitem=obj;                
                index=0;
            }else{
                obj=$scope.delitem;
            }
            //删除的初始值
            $scope.delpaperId.confirmdel=index;
            $scope.delpaperId.paper_id=[];

            if(obj!=undefined&&obj!=""){$scope.selectList=[obj];}

          if ($scope.selectList.length<=0) {
                $scope.isloading=false;
                return Msg.warning("请选择要删除的数据!");
          }else{
                $scope.selectList.forEach(function(element, index) {
                    $scope.delpaperId.paper_id.push(element.paperId);
                });
          }
            if(index==0||index=="0"){
                //提示框
                MsgCon.delnoicon().then(function (flag) {   // 删除弹框
                    if (flag) {
                        $scope.isloading=true;
                        $scope.delcenter($scope.delpaperId);
                    }else{
                        $scope.isloading=false;
                    }
                });
            //删除全部
            }else{
                $scope.delcenter($scope.delpaperId);
            }
    }
    $scope.delcenter=function(param){
          RTS.delPaper(param).then(function(data){
                $scope.isloading=false;
                if (data.errorcode == "0") {
                    $scope.delpaperId.paper_id=[];
                     Msg.success("删除成功");
                     $scope.deleteHide = false; 
                     $scope.GetList();
                }else if (data.errorcode == "34") {   // 获取失败                                         
                    $scope.deleteList = data.datas;
                    $scope.deleteHide = true;   // 显示关联窗口
                }else{
                    Msg.error("请求数据有误");
                }
          });
    }


    /**********************************组卷规则配置*************************************************/
    $scope.questions_Typelist=[
    {name:"不限题型",num:"0"},
    {name:"单选题",num:"1"},
    {name:"多选题",num:"2"},
    {name:"判断题",num:"3"},
    {name:"问答题",num:"4"},
    {name:"填空题",num:"5"},
    {name:"B型题",num:"6"},
    {name:"综合题",num:"7"},
    {name:"找错题",num:"8"}];

//配置知识选择器
     $scope.knowConfigQue = {   // 配置知识选择器的参数
     	menu: ["structure"],
        kssMore:false, //知识结构 是否多选
        kssList:[],    // 知识结构选中列表
        isShow:false,  // 显示知识选择器
    }; 

	//组卷规则
	$scope.newQue=function(){
		return{
			RuleId:guid.newGUID(),
			knowledge_Name:"选择知识",
			knowledge_Id:"",
			paperDifficulty:"0",
			Number_of_questions:0,
			Score_per_question:1,
			questions_Type:"0",
			kssList:[],
			quescount:0
		};
	}

	//查询题目数
	$scope.GetQueCount=function(item){
		$scope.queitem={
			questions_Type:item.questions_Type,
			knowledge_Id:item.knowledge_Id,
			difficulty:item.paperDifficulty,
			userid: sysUserInfo.getuserinfo().user_ID,
	   		orgid: sysUserInfo.getuserinfo().organization_ID,   // 企业id
	   	};

	   	RTS.findNumberByWhere($scope.queitem).then(function(data){
    		// $scope.isloading=false;
    		if (data.errorcode == "0") {
    			item.quescount=data.number;
    		}else{
    			Msg.error("请求数据有误");
    		}
    	});
	   }
	   $scope.knowConfigQueindex= 0;
	//单条题目知识分类回调方法
	$scope.onCallbackSerQue = function(){
		if($scope.knowConfigQue.kssList != null && $scope.knowConfigQue.kssList.length >0){
			$scope.paperObj.Rule[$scope.knowConfigQueindex].kssList = $scope.knowConfigQue.kssList;
			$scope.paperObj.Rule[$scope.knowConfigQueindex].knowledge_Id=$scope.paperObj.Rule[$scope.knowConfigQueindex].kssList[0].knowledge_Id;
			$scope.paperObj.Rule[$scope.knowConfigQueindex].knowledge_Name=$scope.paperObj.Rule[$scope.knowConfigQueindex].kssList[0].knowledge_Name;
			$scope.GetQueCount($scope.paperObj.Rule[$scope.knowConfigQueindex]);
		}else{
            $scope.paperObj.Rule.splice($scope.knowConfigQueindex,1);
        }

	}
	
	var guid = new GUID();

	//添加规则
	$scope.addQuelist=function(){
		var queobj=$scope.newQue();
		$scope.paperObj.Rule.push(queobj);
		var index=$scope.containsQue($scope.paperObj.Rule,queobj);
		$scope.knowConfigQue.isShow=true;
		$scope.knowConfigQueindex = index;
		$scope.knowConfigQue.kssList=$scope.paperObj.Rule[index].kssList;
	}
	//删除规则
	$scope.delQuelist=function(obj){
		$scope.paperObj.Rule.splice($scope.containsQue($scope.paperObj.Rule,obj),1);
	}
	
	$scope.containsQue = function (arr, obj) {
		try {
			var i = arr.length;
			while (i--) {

				if (arr[i].RuleId === obj.RuleId) {
					return i;
				}
			}
			return -1;
		} catch (e) {
            return -1;
        }
    }


//显示提示
    $scope.showrepetitionRate=false;
    $scope.showexamCount=false;
    $scope.showMsg=function(val){
    	switch (val) {
    		case 1:
    		$scope.showrepetitionRate=true;
    		break;
    		case 2:
    		$scope.showexamCount=true;
    		break;

    	}
    }
    //隐藏提示
    $scope.hideMsg=function(val){
    	switch (val) {
    		case 1:
    		$scope.showrepetitionRate=false;
    		break;
    		case 2:
    		$scope.showexamCount=false;
    		break;
    		
    	}
    }
//判定考试分数显示隐藏
$scope.totalScoreShow=function(){
//判定试卷类型
	if ($scope.paperObj.paper_Random==1) {
		//固定卷
		if ($scope.paperObj.paperId=="") {
			return false;
		}else {
			return true;
		}
	}
	else {
		$scope.paperObj.totalScore=0;
        if($scope.paperObj.Rule==undefined&&typeof($scope.paperObj.rule)=="string"){
            $scope.paperObj.Rule=JSON.parse($scope.paperObj.rule)
        }
		$scope.paperObj.Rule.forEach(function(element) {
			$scope.paperObj.totalScore+=element.Score_per_question*element.Number_of_questions;
		});
		
		return true;
	}
}
$scope.urlexamlopen="?id=100&userid="+sysUserInfo.getuserinfo().user_ID,
$scope.urlexamlexcel="?id=100&userid="+sysUserInfo.getuserinfo().user_ID,
$scope.openUrl=function(id,val){
if (val==1) {
  return $rootScope.requestUrl+"/course/paperStatistics?paperid="+id+"&orderby=desc&correct=&sort=1&export=2";
}

}

    /*******************************************************************题库弹窗*****************************************/
    

    $scope.modalStyle={"width":document.body.offsetWidth+"px","height":document.body.offsetHeight+"px"};
    $scope.OpenQueHtml=function(paperid){
      var url="";
      var url2="";
      if ($rootScope.requestUrl.indexOf("http") == -1) {
        url=window.location.protocol;
      }
      if ($rootScope.DeployUrl.indexOf("http") == -1) {
        url2=window.location.protocol;
      }
    	$scope.paper_id=paperid;
    	var endcodeurl=url+$rootScope.requestUrl+'/questionLook/QuestionBydoc?paper_id='+$scope.paper_id+'&id='+sysUserInfo.getuserinfo().user_ID+'&url='+url2+$rootScope.DeployUrl+'/system/views/examination/examend.html';
    	$scope.someUrl = $sce.trustAs($sce.RESOURCE_URL,$rootScope.questionUrl+endcodeurl);
    	$scope.iframeShow=true;
    }
    $scope.closeuser=function(){
    	$scope.iframeShow=false;
    	$scope.someUrl="";
    	
    }
  //页面监听iframe关闭
  $scope.$watch('iframeShow', function (newValue, oldValue, scope) {
  	if (!$scope.iframeShow && $scope.iframeShow != undefined) {
        var examresult="";
  		try{
  		  examresult=JSON.parse(JSON.parse(document.getElementById('itemobj').value).examobj);
  			examresult.create_Date=examresult.create_Date.replace("+"," ");	
  			examresult.upd_Date=examresult.upd_Date.replace("+"," ");
  			
  		}
  		catch(e){
  			console.log(e);
  		}
      if (examresult!="") {
       $scope.GetList();
      }
  	} 
  }, true);

/****************************************************查看成绩********************************************/
    //打开成绩
    $scope.openresultstatic = function (item) {
    var examparam={resultid:item.paperId,url:"",name:item.paperName};
         resultStatisFactory.activate(examparam);
    }

      //打开错题统计
    $scope.openErrorQuestion = function (item) {
        if(item.examCount==undefined||item.examCount==null||item.examCount<=0){
                    return Msg.warning("该试卷还没有学员考试!");
        }
        var examparam={resultid:item.paperId,url:"",name:item.paperName};
         errorQuestionFactory.activate(examparam);
    }
    /*************************** 空路径提示*******************************/
    $scope.examNull = function(){
        Msg.info('提示','试卷中的题目为空请添加题目！');
    }
    /*****************************************************************************************/

    $scope.closeConfirm=function(){
        MsgCon.delnoicon("提示", "确认取消操作吗？", "", "确定", "继续").then(function (data) {
            if (data)
                $scope.windowsClose=false;
        });
    }
    
    //************************************负责人*****************************************//
    // 人员选择器
    //批量添加负责人 选择器初始化
    $scope.personDataUser = {

        ApiOpen: false,
        style: "",
        menu: [{ "id": "User"}],
        UserList: [],
        ViceuserOrgList: [],
        ViceuserRoleList: [],
        ViceuserGroupList: [],
        searchType: [],  //初始化教师查询
        //                 searchTexts: 3,  // 初始化教师查询
        DB: "0",
        DBdata: []

    }
    $scope.mousePosition = function (ev) {
                if (!ev) {
                    ev = window.event;
                }

                if (ev.type != "click") {
                    return;
                }
                var width = 0;
                var height = 0;
                if (ev.pageX || ev.pageY) {//firefox、chrome等浏览器
                    if (document.documentElement.clientWidth - ev.pageX < 450) {
                        width = ev.pageX - (450 - (document.documentElement.clientWidth - ev.pageX)) - 20;
                    } else {
                        width = ev.pageX;
                    }
                    if (document.documentElement.clientHeight - ev.pageY < 480) {
                        height = ev.pageY - (480 - (document.documentElement.clientHeight - ev.pageY)) - 20;
                    } else {
                        height = ev.pageY;
                    }

                    return { "left": width + "px", "top": height + "px", "position": "fixed" };
                }

                return {// IE浏览器
                    "left": ev.clientX + document.body.scrollLeft - document.body.clientLeft,
                    "top": ev.clientY + document.body.scrollTop - document.body.clientTop
                };
            }
    // 新增负责人
    $scope.showPersonSelect = function (event) {
        $scope.personDataUser.style = $scope.mousePosition(event);
        $scope.personDataUser.ApiOpen = true;
    }
    //获取负责人
    $scope.getPerson = function () {
        RTS.findRelationPeople({ userId: sysUserInfo.getuserinfo().user_ID, xid: $scope.paperObj.paper_id, xtype: 2 }).then(function (data) {
            if (data.errorcode == "0" && data.datas != undefined) {
                $scope.personDataUser.UserList = data.datas;
            }
        });
    }
  
}]);



